--[[
    Builder 注入Jass 启动lua

]]
function builder:jass_inject()
    local input = self.temp .. '\\map\\war3map.j'
    local Entry = 'Main'
    if self.type == 'debug' then
        Entry = self.path_map .. '\\scripts\\Main'
    end
    local reg = ( 'Cheat%s-%(%s-"exec%-lua:\\"Entry"' ):replace( 'Entry', Entry:replace('\\','\\\\') )
    local code = ('\ncall Cheat( "exec-lua:\\"Entry\\"" )\n'):replace( 'Entry', Entry:replace('\\','\\\\') ) --注入的启动代码
    jass = read(input)
    local start,last = jass:find([[function main takes nothing returns nothing]], 1, true) --纯文本查找
    if not start then
        print( '(1)Jass注入失败,当前将无法自动载入Main.lua' )
        return
    end

    if jass:match(reg) then
        print ( '(2)Jass注入失败,当前已经存在入口:' .. Entry )
        return --检测到已经存在入口 就不需要注入了
    end

    local regs = {
        {'InitCustomTriggers%s-%(%s-%).-\n',true},
        {'call%s-InitGlobals%s-%(%s-%).-\n',true},--尾
        {'endfunction.-\n',false},--头

    }
    regs[0] = #regs
    local mainlast = last
    for i, cur in ipairs(regs) do
        start,last = jass:find(cur[1], last or mainlast)
        if start then
            if cur[2] then
                jass = jass:sub(1,last) .. code .. jass:sub(last+1)
            else
                jass = jass:sub(1,start-1) .. code .. '\n' .. jass:sub(start)
            end
            break
        end
        if i == regs[0] then
            print('(3)Jass注入失败,当前将无法自动载入Main.lua')
        end
    end

    write(input, jass)
end